import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Icon, Dropdown, Menu, Row, Col, Card, Form, Input, Button, Table, Modal, Select, DatePicker, Divider } from 'antd';
import styles from './List.less';
import globalConstant from '../../utils/globalConstant';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import AddPackage from './AddPackage';
import ShowPackageInfo from './ShowPackageInfo';
import UpdatePackage from './UpdatePackage';


const FormItem = Form.Item;
const { Option } = Select;


@connect(({ packages, general, loading }) => ({
  packages,
  general,
  loading: loading.models.packages,
}))
@Form.create()
export default class PackageManagement extends Component {
  state = {
    showPackageInfoVisible: false,
    showPackageUpdateVisible: false,
    showPackageAddVisible: false,
    packageId: undefined,
    pageNum: globalConstant.paging.defaultPageNum,
    pageSize: globalConstant.paging.defaultPageSize,
    form: {},
  }
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'packages/getPackagePage',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
    dispatch({
      type: 'general/getDistrictList',
    });
  }
  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.state.form,
    };
    this.setState({
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    });
    dispatch({
      type: 'packages/getPackagePage',
      payload: params,
    });
  }
  handleSearch = (e) => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const invalidValue = fieldsValue.invalidTime || undefined;
      const releaseValue = fieldsValue.releaseTime || undefined;
      dispatch({
        type: 'packages/getPackagePage',
        payload: {
          packageStatus: fieldsValue.packageStatus === -1 ? null : fieldsValue.packageStatus,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          keywordsValue: fieldsValue.keywordsValue || null,
          invalidTimeEnd: invalidValue && invalidValue[1].valueOf(),
          invalidTimeStart: invalidValue && invalidValue[0].valueOf(),
          releaseTimeEnd: releaseValue && releaseValue[1].valueOf(),
          releaseTimeStart: releaseValue && releaseValue[0].valueOf(),
        },
      });
      this.setState({
        form: {
          packageStatus: fieldsValue.packageStatus === -1 ? null : fieldsValue.packageStatus,
          districtId: fieldsValue.districtId === -1 ? null : fieldsValue.districtId,
          keywordsValue: fieldsValue.keywordsValue || null,
          invalidTimeEnd: invalidValue && invalidValue[1].valueOf(),
          invalidTimeStart: invalidValue && invalidValue[0].valueOf(),
          releaseTimeEnd: releaseValue && releaseValue[1].valueOf(),
          releaseTimeStart: releaseValue && releaseValue[0].valueOf(),
        },
      });
    });
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      form:{},
    });
    dispatch({
      type: 'packages/getPackagePage',
      payload: {
        pageNum: globalConstant.paging.defaultPageNum,
        pageSize: globalConstant.paging.defaultPageSize,
      },
    });
  }
  handlePackageInfoModal= (text) => {
    this.setState({
      packageId: text.id,
      showPackageInfoVisible: true,
    });
  }
  handlePackageInfoModalCancel =(refreshFlag) => {
    if (refreshFlag) {
      this.props.dispatch({
        type: 'packages/getPackagePage',
        payload: {
          pageNum: globalConstant.paging.defaultPageNum,
          pageSize: globalConstant.paging.defaultPageSize,
          ...this.state.form,
        },
      });
    }
    this.setState({
      showPackageInfoVisible: false,
    });
  }
  handlePackageUpdateModal= (text) => {
    this.setState({
      packageId: text.id,
      showPackageUpdateVisible: true,
    });
  }
  handlePackageUpdateModalCancel =() => {
    this.setState({
      showPackageUpdateVisible: false,
    });
  }
  handlePackageAddModal= () => {
    this.setState({
      showPackageAddVisible: true,
    });
  }
  handlePackageAddModalCancel =(refreshFlag) => {
    if (refreshFlag) {
      const { dispatch } = this.props;
      dispatch({
        type: 'packages/getPackagePage',
        payload: {
          pageNum: this.state.pageNum,
          pageSize: this.state.pageSize,
          ...this.state.form,
        },
      });
    }
    this.setState({
      showPackageAddVisible: false,
    });
  }
  handleChildUpdateModal =(refreshFlag) => {
    if (refreshFlag) {
      const { dispatch } = this.props;
      dispatch({
        type: 'packages/getPackagePage',
        payload: {
          pageNum: this.state.pageNum,
          pageSize: this.state.pageSize,
        },
      });
    }
    this.setState({
      showPackageUpdateVisible: false,
    });
  }
  handleMenuClick =(e) => {
    console.log(e);
  }
  showDeleteConfirm =(text) => {
    Modal.confirm({
      title: '确定删除?',
      content: '删除无法恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        const { dispatch } = this.props;
        dispatch({
          type: 'packages/deletePackage',
          payload: {
            id: text.id,
          },
          callback: () => {
            dispatch({
              type: 'packages/getPackagePage',
              payload: {
                pageNum: this.state.pageNum,
                pageSize: this.state.pageSize,
                ...this.state.form,
              },
            });
          },
        });
      },
    });
  }
  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    const { general: { districtList } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="关键字">
              {getFieldDecorator('keywordsValue')(
                <Input placeholder="请输入搜索关键字" />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="状态">
              {getFieldDecorator('packageStatus')(
                <Select>
                  {
                    globalConstant.packageStatus.map((item) => {
                      return (
                        <Option
                          key={item.id.toString()}
                          value={item.value}
                        >{item.label}
                        </Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          {/*<Col span={8}>*/}
            {/*<FormItem label="区域">*/}
              {/*{getFieldDecorator('districtId')(*/}
                {/*<Select>*/}
                  {/*{*/}
                    {/*districtList.map((item) => {*/}
                      {/*return (*/}
                        {/*<Option*/}
                          {/*key={item.id.toString()}*/}
                          {/*value={item.id}*/}
                        {/*>{item.districtName}*/}
                        {/*</Option>*/}
                      {/*);*/}
                    {/*})*/}
                  {/*}*/}
                {/*</Select>*/}
              {/*)}*/}
            {/*</FormItem>*/}
          {/*</Col>*/}
        </Row>
        <Row gutter={24}>
          <Col span={8}>
            <FormItem label="上架时间">
              {getFieldDecorator('releaseTime', {
              })(
                <DatePicker.RangePicker
                  format={globalConstant.dateFormat}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="下架时间">
              {getFieldDecorator('invalidTime')(
                <DatePicker.RangePicker
                  format={globalConstant.dateFormat}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col span={8} style={{ textAlign: 'right' }}>
            <span className={styles.submitButtons}>
              <Button icon="search" type="primary" htmlType="submit" >查询</Button>
              <Button icon="reload" style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const { packages: { packageList }, loading } = this.props;
    const {
      showPackageInfoVisible,
      showPackageAddVisible,
      showPackageUpdateVisible,
      packageId,
    } = this.state;
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        width: '10%',
      },
      {
        title: '套餐名称',
        dataIndex: 'packageName',
        width: '15%',
      },
      {
        title: '业务类型',
        dataIndex: 'bussinessNameTransient',
        width: '10%',
      },
      {
        title: '套餐价格',
        dataIndex: 'packagePrice',
        width: '10%',
      },
      {
        title: '带宽',
        dataIndex: 'networkSpeed',
        width: '10%',
      },
      {
        title: '发布状态',
        dataIndex: 'packageStatusNameTransient',
        width: '10%',
      },
      {
        title: '下架时间',
        dataIndex: 'invalidTime',
        width: '15%',
        render: (text) => {
          return moment(text).format(globalConstant.dateFormat);
        },
      },
      {
        title: '操作',
        key: 'key',
        render: (text) => {
          const menu = (
            <Menu onClick={this.handleMenuClick}>
              <Menu.Item key="1">
                <Button type="primary" icon="info" onClick={() => { this.handlePackageInfoModal(text); }} >
                  查看
                </Button>
              </Menu.Item>
              <Menu.Item key="2">
                <Button type="primary" icon="edit" onClick={() => { this.handlePackageUpdateModal(text); }} disabled={text.packageStatus === 'NETWORK_PACKAGE_STATUS_RELEASE'} >
                  修改
                </Button>
              </Menu.Item>
              <Menu.Item key="3">
                <Button type="danger" icon="delete" onClick={() => { this.showDeleteConfirm(text); }} disabled={text.packageStatus === 'NETWORK_PACKAGE_STATUS_RELEASE'} >
                  删除
                </Button>
              </Menu.Item>
            </Menu>
          );
          return (
            <Dropdown overlay={menu}>
              <Button style={{ width: 100 }}>
                操作 <Icon type="down" />
              </Button>
            </Dropdown>
          );
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      total: packageList && packageList.totals,
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
      ...globalConstant.pagingFormat,
    };
    return (
      <PageHeaderLayout title="套餐管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>
              {this.renderSimpleForm()}
            </div>
            <Divider />
            <Card bordered>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handlePackageAddModal()}>
                  添加
                </Button>
              </div>
              <Table
                bordered
                rowKey={record => record.id}
                loading={loading}
                dataSource={packageList && packageList.items}
                columns={columns}
                pagination={paginationProps}
                onChange={this.handleStandardTableChange}
              />
            </Card>
          </div>
        </Card>
        <Modal
          visible={showPackageInfoVisible}
          title="查看详情"
          footer={null}
          width="60%"
          onCancel={() => this.handlePackageInfoModalCancel()}
          destroyOnClose
        >
          <ShowPackageInfo
            childShowInfo={this.handlePackageInfoModalCancel.bind(this)}
            packageId={packageId}
          />
        </Modal>
        <Modal
          visible={showPackageUpdateVisible}
          title="套餐修改"
          footer={null}
          width="60%"
          onCancel={() => this.handlePackageUpdateModalCancel()}
          destroyOnClose
        >
          <UpdatePackage
            packageId={packageId}
            handleUpdateMoadl={this.handleChildUpdateModal.bind(this)}
          />
        </Modal>
        <Modal
          visible={showPackageAddVisible}
          title="添加套餐"
          footer={null}
          width="60%"
          onCancel={() => this.handlePackageAddModalCancel()}
          destroyOnClose
        >
          <AddPackage closeModal={this.handlePackageAddModalCancel.bind(this)} />
        </Modal>
      </PageHeaderLayout>
    );
  }
}
